<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <!-- <label class="el-form-item-label">ip地址</label>
        <el-input v-model="query.ip" clearable placeholder="ip地址" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">编号</label>
        <el-input v-model="query.no" clearable placeholder="编号"  style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <label class="el-form-item-label">实验室</label>
        <!-- <el-input v-model="query.labId" clearable placeholder="实验室" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <el-select
          v-model="query.labId"
          placeholder="请选择实验室"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in labs" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="ip地址" prop="ip">
            <el-input v-model="form.ip" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="编号" prop="no">
            <el-input v-model="form.no" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="实验室" prop="labId">
            <el-select
              v-model="form.labId"
              placeholder="请选择实验室"
              style="width: 370px;"
            >
              <el-option v-for="item in labs" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.note" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" />
        <!-- <el-table-column prop="ip" label="ip地址" /> -->
        <!-- <el-table-column prop="devSerialNum" label="编号" /> -->
        <el-table-column prop="labName" label="实验室" :formatter="formatterLab" />
        <el-table-column prop="note" label="备注" />
        <el-table-column label="状态">
           <template slot-scope="scope">
              <span v-if="scope.row.isOpen==1">开门状态</span>
              <span v-else-if="scope.row.isOpen==0">关门状态</span>
           </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','entranceGuard:edit','entranceGuard:del'])" label="操作" width="180px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
            <el-button
              type="success"
              class="isForbiddenBtn"
              @click.native="IsOpenDoor(scope.row)"
            >{{ scope.row.isOpen ==1 ? "关门" : scope.row.isOpen ==0 ?"开门" : "- -" }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import getAllUserAndLabs from '@/mixins/getAllUserAndLabs.js'
import crudEntranceGuard,{controlGuardAPI} from '@/api/entranceGuard'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, ip: null, no: null, note: null, labId: null, createdAt: null, updatedAt: null, isDeleted: null }
export default {
  name: 'EntranceGuard',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud(), getAllUserAndLabs],
  cruds() {
    return CRUD({ title: '门禁', url: 'api/entranceGuard', idField: 'id', sort: 'id,desc', crudMethod: { ...crudEntranceGuard }})
  },
  data() {
    const limitNumber = (rule, value, callback) => {
      if (value) {
        if (!Number.isInteger(+value)) {
          callback(new Error('必须全为数字'))
        }
        //  else if (value.trim().length < 8 || value.trim().length > 12) {
        //   callback(new Error('数字长度必须在8到12之间'))
        // }
        else {
          callback()
        }
      } else if (rule.required) {
        // 如果没值又是必填
        callback(new Error(rule.msg))
      } else {
        callback()
      }
    }
    return {
      permission: {
        add: ['admin', 'entranceGuard:add'],
        edit: ['admin', 'entranceGuard:edit'],
        del: ['admin', 'entranceGuard:del']
      },
      rules: {
        ip: [
          { required: true, message: 'ip地址不能为空', trigger: 'blur' }
        ],
        no: [
          { validator: limitNumber, message: '请输入正确的数据格式', trigger: 'blur' },
          { required: true, message: '编号不能为空', trigger: 'blur' }
        ],
        labId: [
          { required: true, message: '实验室不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'ip', display_name: 'ip地址' },
        { key: 'no', display_name: '编号' },
        { key: 'labId', display_name: '实验室' }
      ]
    }
  },
  created() {
    this.getLabs()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    formatterLab(row) {
      const data = this.labs.find(lab => lab.id == row.labId)
      if (data) {
        return data.name
      }
    },
    async IsOpenDoor(row){
      if(row.isOpen == 0||row.isOpen ==1){
        const oldIsOPen = row.isOpen ==1? 0:1
        try {
           await controlGuardAPI({
              id:row.id,
              state:row.isOpen
           })
           row.isOpen = oldIsOPen
        } catch (error) {
          this.$message.error('操作失败')
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.el-table ::v-deep .cell {
  display: flex;
  align-items: center;

  .isForbiddenBtn {
    width: 43px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    margin-left: 5px;
    padding: 0;
  }
}
</style>
